/*
 * Copyright (c) 2019-2029, Dreamlu 卢春梦 (596392912@qq.com & www.dreamlu.net).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.lybgeek.pf4j.processor;

import com.github.lybgeek.pf4j.util.StringUtils;
import lombok.experimental.UtilityClass;

import javax.lang.model.util.Elements;
import javax.tools.FileObject;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * spring boot 自动化配置工具类
 *
 * @author L.cm
 */
@UtilityClass
class PluginConfigFiles {
	private static final Charset UTF_8 = StandardCharsets.UTF_8;

	/**
	 * 读取 plugin.properties 文件
	 *
	 * @param fileObject FileObject
	 * @return MultiSetMap
	 * @throws IOException 异常信息
	 */
	protected static Map<String, String> readPluginFile(FileObject fileObject, Elements elementUtils) throws IOException {
		// 读取 plugin.properties 内容
		Properties properties = new Properties();
		try (InputStream input = fileObject.openInputStream()) {
			properties.load(input);
		}
		Map<String, String> map = new LinkedHashMap<>();
		Set<Map.Entry<Object, Object>> entrySet = properties.entrySet();
		for (Map.Entry<Object, Object> objectEntry : entrySet) {
			String key = (String) objectEntry.getKey();
			String value = (String) objectEntry.getValue();
			if (value == null || value.trim().isEmpty()) {
				continue;
			}
			map.put(key.trim(), value);
		}
		return map;
	}



	/**
	 * 写出 plugin.properties  文件
	 *
	 * @param pluginProperiesFields pluginProperiesFields 信息
	 * @param output    输出流
	 * @throws IOException 异常信息
	 */
	protected static void writePluginFile(Map<String, String> pluginProperiesFields,
											 OutputStream output) throws IOException {
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, UTF_8));
		writer.write("# Generated by lyb-geek www.github.org\n");
		Set<String> keySet = pluginProperiesFields.keySet();
		for (String key : keySet) {
			String value = pluginProperiesFields.get(key);
			if (StringUtils.isBlank(value)) {
				continue;
			}
			writer.write(key);
			writer.write("=");
			StringJoiner joiner = new StringJoiner(",\\\n  ");
			joiner.add(value);
			writer.write(joiner.toString());
			writer.newLine();
		}
		writer.flush();
	}



}
